package com.hw8.utils;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import net.spy.memcached.MemcachedClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class MemcacheUtils {
    private static MemcachedClient memcachedClient;
    @Resource
    public void setMemcachedClient(MemcachedClient memcachedClient){
        MemcacheUtils.memcachedClient = memcachedClient;
    }

    public static Long getParentId(long userId) {
        String key = generateKey(userId);
        String value = (String)memcachedClient.get(key);
        if(value == null){
            log.error("userId = {},缓存没有找到信息");
            return 0l;
        }
        Long parentId = JSON.parseObject(value).getLong("parentId");
        return parentId;
    }

    private static String generateKey(long userId) {
        return String.format("UserInfo_%d", userId);
    }

    public static List<Long> get30TierParentIds(long userId) {
        List<Long> parentIds = new ArrayList<>(30);
        for (int i = 0; i < 30; i++) {
            Long parentId = getParentId(userId);
            if(parentId == 0){
                break;
            }
            parentIds.add(parentId);
            userId = parentId;
        }
        return parentIds;
    }

}
